package com.doge.walknovel.business.search

import androidx.lifecycle.MutableLiveData
import com.doge.walknovel.core.base.adapters.add
import com.doge.walknovel.core.base.adapters.remove
import com.doge.walknovel.utils.*
import com.google.gson.reflect.TypeToken

object SearchHistoryHelper {
    private const val key = "searchKey"
    private const val folder = "search"
    val currentHistoryKeys = MutableLiveData<List<String>>()

    fun initialized() {       // 进入搜索页面
        currentHistoryKeys.value = currentHistoryKeys.value ?: spReadString(key, null, folder).let {
            fromJson<List<String>>(it, object : TypeToken<List<String>>() {}.type) ?: listOf()
        }
    }

    fun recordNewKey(value: String?) {
        if (value.isNullOrEmpty()) return
        val last: List<String> = currentHistoryKeys.value ?: listOf()
        val result = last.remove(value).add(0, value)
        currentHistoryKeys.value = result
        runOnIO {
            spWrite(key, toJson(result), folder)
        }
    }

    fun clear() {
        currentHistoryKeys.value = listOf()
        runOnIO { spWrite(key, "", folder) }
    }
}